<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {
  NForm,
  NFormItem,
  NInputNumber,
  NButton,
  NGrid,
  NGi
} from 'naive-ui'
import { invoke } from '@tauri-apps/api'

const windowRect = ref([0, 0, 1920, 1080])

async function onAction(action: string, args: Any) {
  const err = await invoke(action, { args })
  if(err) {
    console.error(err)
  } else {
    cache(action, args)
  }
}
function load(key: string) {
  try {
    return JSON.parse(localStorage.getItem(key) || '-')
  } catch {}
  return null
}
function cache(key: string, data: Any) {
  try {
    localStorage.setItem('__' + key + '__', JSON.stringify(data))
  } catch {}
}
onMounted(() => {
  const rect = load('__set_position__')
  if (rect) {
    windowRect.value = rect
  }
})
</script>

<template>
  <div class="tools">
    <n-form label-width="60" label-placement="left" size="medium">
      <n-grid cols="24" x-gap="0" y-gap="0">
        <n-gi span="8">
          <n-grid cols="17" x-gap="0" y-gap="0">
            <n-gi span="14" offset="3">
              <div class="title">窗口定位:</div>
            </n-gi>
            <n-gi span="17">
              <n-form-item label="X">
                <n-input-number :show-button="false" v-model:value="windowRect[0]" :precision="0" :min="0" :max="8192" />
              </n-form-item>
            </n-gi>
            <n-gi span="17">
              <n-form-item label="Y">
                <n-input-number :show-button="false" v-model:value="windowRect[1]" :precision="0" :min="0" :max="8192" />
              </n-form-item>
            </n-gi>
            <n-gi span="17">
              <n-form-item label="宽度">
                <n-input-number :show-button="false" v-model:value="windowRect[2]" :precision="0" :min="0" :max="8192" />
              </n-form-item>
            </n-gi>
            <n-gi span="17">
              <n-form-item label="高度">
                <n-input-number :show-button="false" v-model:value="windowRect[3]" :precision="0" :min="0" :max="8192" />
              </n-form-item>
            </n-gi>
            <n-gi span="5" offset="12">
              <n-button type="primary" block @click="onAction('set_position', Object.values(windowRect))">设置</n-button>
            </n-gi>
          </n-grid>
        </n-gi>
      </n-grid>
    </n-form>
  </div>
</template>

<style scoped lang="less">
.tools {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .title {
    font-weight: bold;
    padding-bottom: 12px;
  }
}
</style>
